<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018-12-17
 * Time: 14:27
 */

namespace Ekaipiao;

use app\common\model\Merchant;

class Epiao
{
    const API_URL = "http://ek.caikaixin.cn/";

    public function register($data)
    {
        $result = $this->http_post(self::API_URL . "register", self::json_encode($data));
        if ($result) {
            $json = json_decode($result, true);
            return $json;
        }
        return false;
    }
    public function token($mid)
    {
        $Merchant=new Merchant();
        $tk_info=$Merchant->where('id',$mid)->field('efp_token,efp_time,efp_invoice,efp_kpjh')->find();
        if($tk_info['efp_time']+7000<=time()){
            $data=array(
                "invoice"=>$tk_info['efp_invoice'],
                "kpjh"=>$tk_info['efp_kpjh'],
            );
            $result = $this->http_post(self::API_URL . "token", self::json_encode($data));
            if ($result) {
                $token = json_decode($result, true);
                if($token['errcode']=="200"){
                    $tokens= $token['info'][0]['token'];
                    $Merchant->save(['efp_token'=>$tokens,'efp_time'=>time()],['id'=>$mid]);
                }else{
                    return $token;
                }

            }
        }else{
            $tokens=$tk_info['efp_token'];
        }

        return $tokens;
    }

    public function kaipiao($data)
    {
//        return $data['xml'];
        $ase = new AesJava();
        $array = $ase->encrypt($data['xml'],$data['invoice']);
        $data['spxx'] = $array;
        unset($data['xml']);
//        return $data;
//        return $data;
        $result = $this->http_post(self::API_URL . "sendFpInfo", self::json_encode($data));
        if ($result) {
            $json = json_decode($result, true);
            return $json;
        }
        return false;
    }

    private function arr2xml($data, $root = false)
    {
        $str = "";
        if ($root) $str .= "<xml>";
        foreach ($data as $key => $val) {
            //去掉key中的下标[]
            $key = preg_replace('/\[\d*\]/', '', $key);
            if (is_array($val)) {
                $child = $this->arr2xml($val, false);
                $str .= "<$key>$child</$key>";
            } else {
                $str .= "<$key><![CDATA[$val]]></$key>";
            }
        }
        if ($root) $str .= "</xml>";
        return $str;
    }

    private function http_post($url, $param, $post_file = false)
    {

        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
            $is_curlFile = true;
        } else {
            $is_curlFile = false;
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        if (is_string($param)) {
            $strPOST = $param;
        } elseif ($post_file) {

            if ($is_curlFile) {
                foreach ($param as $key => $val) {

                    if (substr($val, 0, 1) == '@') {

                        $param[$key] = new \CURLFile(realpath(substr($val, 1)));

                    }
                }

            }
            $strPOST = $param;

        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);

        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($strPOST)
            )
        );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);

        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    function json_encode($arr)
    {
        return json_encode($arr, JSON_UNESCAPED_UNICODE);
    }
}
